/**
 * Copyright (C) 2010 VMWare, Inc. All Rights Reserved
 */

package org.loujiarong.yugioh.gameplay.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * DatabaseCoordinator is the main class of database connection pool management
 *
 * @author jlou
 */
public class DatabaseCoordinator {
   private static List<Connection> connectionPool;     // Connection pool to reuse connection
   private static String jdbcDriver;                   // DB driver class
   private static String jdbcURL;                      // DB URL
   private static String userName;                     // DB userName
   private static String password;                     // DB password

   /**
    * Initialize database parameters
    * @param jdbcDriver DB driver class
    * @param jdbcURL DB URL
    */
   public static void
   initialize(String jdbcDriver,
              String jdbcURL,
              String userName,
              String password) {
      DatabaseCoordinator.jdbcDriver = jdbcDriver;
      DatabaseCoordinator.jdbcURL = jdbcURL;
      DatabaseCoordinator.userName = userName;
      DatabaseCoordinator.password = password;
      DatabaseCoordinator.connectionPool = new ArrayList<Connection>();
   }

   /**
    * Check connection pool and get an idle or new connection
    * @return An idle or new connection
    */
   public synchronized static Connection
   getConnection() {
      try {
         // loop until getting a valid connection from connection pool
         while (connectionPool.size() > 0) {
            Connection conn = connectionPool.remove(connectionPool.size() - 1);
            if (conn != null && !conn.isClosed()) {
               return conn;
            }
         }

         Class.forName(jdbcDriver);
         return DriverManager.getConnection(jdbcURL, userName, password);
      }
      catch (ClassNotFoundException e) {
      }
      catch (SQLException e) {
      }
      return null;
   }

   /**
    * Recycle connection and put in idle state
    * @param con The connection to recycle
    */
   public synchronized static void
   releaseConnection(Connection con) {
      connectionPool.add(con);
   }
}
